<template>
  <div ref="container" class="game"></div>
</template>

<script>
const WHS = require('whs')
const PHYSICS = require('physics-module-ammonext')
const THREE = require('three')
export default {
  mounted () {
    this.init()
  },
  data () {
    return {
      app: null,
      ball: null
    }
  },
  methods: {
    init () {
      this.app = new WHS.App([
        new WHS.ElementModule({
          container: this.$refs['container']}),
        new WHS.SceneModule(),
        new WHS.DefineModule('camera', new WHS.PerspectiveCamera({
          position: new THREE.Vector3(0, 10, 50)
        })),
        new WHS.RenderingModule({
          bgColor: 0x000000,
          bgOpacity: 1,
          renderer: {
            antialias: true,
            shadowmap: {
              type: THREE.PCFSoftShadowMap
            }
          }
        }, {shadow: true}),
        new WHS.OrbitControlsModule(),
        new WHS.ResizeModule()
      ])
      // plane
      new WHS.Plane({
        geometry: {
          width: 100,
          height: 100
        },
        material: new THREE.MeshPhongMaterial({
          color: 0x447F8B
        }),
        rotation: {
          x: -Math.PI / 2
        }
      }).addTo(this.app)
      // light
      new WHS.PointLight({
        light: {
          intensity: 0.5,
          distance: 100
        },
        shadow: {
          fov: 90
        },
        position: new THREE.Vector3(0, 10, 10)
      }).addTo(this.app)
      new WHS.AmbientLight({
        light: {
          intensity: 0.5
        }
      }).addTo(this.app)
      // obj
      const sphere = new WHS.Sphere({
        geometry: {
          radius: 5,
          widthSegments: 32,
          heightSegments: 32
        },
        material: new THREE.MeshPhongMaterial({
          color: 0xF2F2F2
        }),
        position: new THREE.Vector3(0, 20, 0),
        modules: [
          new PHYSICS.SphereModule({
            mass: 10
          })
        ]
      })
      sphere.addTo(this.app)
      this.ball = sphere
      this.app.start()
      window.addEventListener('keydown', this.control)
      new WHS.Loop((clock) => {
        sphere.position.y = 10 * Math.sin(clock.getElapsedTime()) + 15
      }).start(this.app)
    },
    control (e, ball = this.ball) {
      switch (e.keyCode) {
        case 87:
          ball.position.y += 10
          break
        case 83:
          ball.position.y -= ball.position.y - 10 <= 5 ? 0 : 10
          break
        case 65:
          ball.position.x -= 5
          break
        case 68:
          ball.position.x += 5
      }
    }
  }
}
</script>

<style scoped>
.game {
}
</style>
